// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2022 Ivan Baidakou

#include "board.h"
#include "rotor-light.hpp"

#ifdef __MICROBLAZE__

#include "xgpio.h"
#include "xparameters.h"

#endif

namespace rl = rotor_light;

namespace message {
struct Ping : rl::Message {
  using Message::Message;
  static constexpr auto type_id = __LINE__;
  rl::MessageTypeId get_type_id() const override { return type_id; }
};

struct Pong : rl::Message {
  using Message::Message;
  static constexpr auto type_id = __LINE__;
  rl::MessageTypeId get_type_id() const override { return type_id; }
};
} // namespace message

struct Pinger : rl::Actor<2> {
  using Parent = Actor<2>;

  void initialize() override {
    subscribe(&Pinger::on_pong);
    Parent::initialize();
  }

  void advance_start() override {
    Parent::advance_start();
    ping();
  }

  void ping() {
    --left;
    send<message::Ping>(0, ponger_id);
  }

  void on_pong(message::Pong &) {
    if (left > 0) {
      ping();
    }
  }

  uint32_t left;
  rl::ActorId ponger_id;
};

struct Ponger : rl::Actor<2> {
  using Parent = Actor<2>;

  void initialize() override {
    subscribe(&Ponger::on_ping);
    Parent::initialize();
  }
  void on_ping(message::Ping &) { send<message::Pong>(0, pinger_id); }
  rl::ActorId pinger_id;
};

using Supervisor =
    rl::Supervisor<rl::SupervisorBase::min_handlers_amount, Pinger, Ponger>;
using Storage = rl::traits::MessageStorage<rl::message::ChangeState,
                                           rl::message::ChangeStateAck,
                                           message::Ping, message::Pong>;
using Queue = rl::Queue<Storage, 5>; /* upto 5 messages in 1 queue */

#ifdef __arm__
constexpr uint32_t amount = 1000000;
void on_start() {}
void on_finish() {}

#elif __MICROBLAZE__
#define GPIO_OUTPUT_DEVICE_ID XPAR_GPIO_0_DEVICE_ID
#define LED_CHANNEL 1

XGpio GpioOutput;

constexpr uint32_t amount = 100000;
void on_start() {
  XGpio_Out32(GpioOutput.BaseAddress + XGPIO_DATA_OFFSET, 0xFFFF);
}
void on_finish() {
  XGpio_Out32(GpioOutput.BaseAddress + XGPIO_DATA_OFFSET, 0x0000);
}
#endif

Supervisor sup;

int main(int, char **) {
  Board::init_start();
  Board::enable_timer();
  Board::enable_interrupts();

#ifdef __MICROBLAZE__
  if (XGpio_Initialize(&GpioOutput, GPIO_OUTPUT_DEVICE_ID) != XST_SUCCESS) {
    return XST_FAILURE;
  }
  XGpio_SetDataDirection(&GpioOutput, LED_CHANNEL, 0x0);
#endif

  while (true) {
    Queue queue;
    rl::Context context{&queue, nullptr, nullptr};

    /* setup */
    sup.bind(context);
    auto pinger = sup.get_child<0>();
    auto ponger = sup.get_child<1>();
    pinger->left = Board::samples;
    pinger->ponger_id = ponger->get_id();
    ponger->pinger_id = pinger->get_id();

    /* disable polling timer timer */
    sup.start(false);
    Board::toggle_led();
    sup.process();
    Board::toggle_led();

    sup.stop();
    sup.process();
    Board::delay();
  }
}
